Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
Javascript | Validate structure of object based on custom schema

Working on a API that needs to validate the strucutre of the incoming request object. Based on other answers to similar questions, I have tried to create a solution that doesn't seem to be working.

My code so far:

 const testObj = {
            "uuid": {
                "value": "5481da7-8b7-22db-d326-b6a0a858ae2f",
                "type": "id"
            },
            "rate": {
                "value": 0.12,
                "type": "percent"
            }
        }

        let ok = true;

        ok = testObj === OBJECT_SCHEMA; // is false. Expected to be true

My validation schema:

const OBJECT_SCHEMA = {
    "uuid": {
        "value": String,
        "type": String
    },
    "rate": {
        "value": Number,
        "type": String
    }
}

Can aynone pinpoint what I'm doing wrong here?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

testObj === OBJECT_SCHEMA is returning false because the value of testObj and OBJECT_SCHEMA types are equal but not values.

My recommendation would be to checkout Yup or Zod for creating a validation

about 4 years ago · Juan Pablo Isaza Report

0

Something to get you started:

let validate = (obj, schema) =>
    typeof obj === 'object'
        ? Object.keys(schema).every(k => validate(obj[k], schema[k]))
        : obj?.constructor === schema;

//

const OBJECT_SCHEMA = {
    "uuid": {
        "value": String,
        "type": String
    },
    "rate": {
        "value": Number,
        "type": String
    }
}


testObj = {
    "uuid": {
        "value": "5481da7-8b7-22db-d326-b6a0a858ae2f",
        "type": "id"
    },
    "rate": {
        "value": 0.12,
        "type": "percent"
    }
}

console.log(validate(testObj, OBJECT_SCHEMA))
testObj.rate.value = 'foo'
console.log(validate(testObj, OBJECT_SCHEMA))
delete testObj.rate.value
console.log(validate(testObj, OBJECT_SCHEMA))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!